﻿using UnityEngine;
using UnityEngine.Events;

namespace LoginUI.UI
{
    public abstract class BasePanel : MonoBehaviour
    {
        // showMe hideMe 方法更新变量状态, Update 中根据变量状态来显示或隐藏面板
        private bool isShow;

        private CanvasGroup canvasGroup;

        // 淡入淡出速度
        private float alphaSpeed = 10f;

        // 记录一个外部传入回调函数
        private UnityAction callback;

        private void Awake()
        {
            canvasGroup = GetComponent<CanvasGroup>();
            // 如果没有 CanvasGroup 组件,则添加一个
            if (canvasGroup == null) canvasGroup = gameObject.AddComponent<CanvasGroup>();
        }


        // 每个面板都有自己的初始化方法
        public abstract void Init();

        public void hideMe(UnityAction hideCallback = null)
        {
            isShow = false;
            canvasGroup.alpha = 1;
            callback = hideCallback;
        }

        public virtual void ShowMe()
        {
            isShow = true;
            canvasGroup.alpha = 0;
        }

        public void Update()
        {
            // 按照 Time.deltaTime 来控制淡入淡出速度
            // 淡入: 0 -> 1 (为1时结束)
            if (isShow)
            {
                if (canvasGroup.alpha >= 1) return;
                canvasGroup.alpha += alphaSpeed * Time.deltaTime;
                if (canvasGroup.alpha >= 1) canvasGroup.alpha = 1;
            } else if (!isShow)
                // 淡出: 1 -> 0, 当 alpha 小于 0 时, 删除自己
            {
                canvasGroup.alpha -= alphaSpeed * Time.deltaTime;
                if (canvasGroup.alpha <= 0)
                {
                    canvasGroup.alpha = 0;
                    // 淡出结束, 删除自己
                    callback?.Invoke();
                }
            }
        }
    }
}